let id = localStorage.getItem("id");
/*  购物车列表 */
function loadCartList(){
    let url='http://jx.xuzhixiang.top/ap/api/cart-list.php'
    $.get(url,{id}).then(r=>{
        console.log(r);
        console.log(r.data.length);
        localStorage.setItem("sl",r.data.length)
        let liArr=r.data.map(v=>`
        <div class="shangpin1">
            <input class="danxuan" style="zoom: 200%" type="checkbox" onchange="singleIptChange(this)" />
            <img src="${v.pimg}" alt="" />
            <h2>${v.pname}</h2>
            <p>${v.pprice}</p>
            <input type="number" value="${v.pnum}" style="zoom: 120%"  data-pid="${v.pid}" data-pprice="${v.pprice}" class="sl" min="1"  />
            <p><span class="line-count">${v.pnum * v.pprice}</span></p>
            <button onclick="cartDeleteClick(${v.pid},this)">x</button>
          </div>
        `)
        $(".shangpin").html(liArr.join(""));
        $(".ddsl").html(r.data.length)
       
        /* 修改 */
        $(".sl").change(function(){
            let pnum = $(this).val()
            let pid = $(this).attr("data-pid")
            let pprice = $(this).attr("data-pprice")
            console.log(pnum,pid);
            let url='http://jx.xuzhixiang.top/ap/api/cart-update-num.php'
            $.get(url,{pid,uid:id,pnum},function(v){
                console.log(v);
                countPriceHandle()
            })
            /* 小计 */
            let currentCoun = pnum*pprice
            $(this).parent().find(".line-count").html(currentCoun)

        })

    })
}
loadCartList()
function cartDeleteClick(pid,btn){
    let url='http://jx.xuzhixiang.top/ap/api/cart-delete.php'
    $.get(url,{uid:id,pid},function(v){
        console.log(v);
        // loadCartList()
        // 删除键
        $(btn).parent().remove();
        countPriceHandle()
    })
   
}

/*  全选按钮 */
function allIptChange(allIpt){
    console.log(allIpt);
    console.log(allIpt.checked);
    document.querySelectorAll(".danxuan").forEach((v) => (v.checked = allIpt.checked))
    countPriceHandle()
}
/* 单选按钮 */
function singleIptChange(singleIpt){
    console.log(singleIpt);
   let singleIpts= document.querySelectorAll(".danxuan")
   let singleArr=Array.from(singleIpts)
   console.log(singleIpts);
   console.log(singleArr);
   let isArr=singleArr.every(ipt=>ipt.checked == true)
   document.querySelector("#all-ipt").checked=isArr
   countPriceHandle()
}
/* 计算总价 */
function countPriceHandle(){
    let singleIpts= document.querySelectorAll(".danxuan");
    // 伪数组转为真数组
    let singleArr=Array.from(singleIpts)
   // 过滤出所有被选中的
    let allArr=singleArr.filter((v)=>v.checked == true)
    console.log(allArr);
    let count = 0;
    allArr.forEach((ipt) => {
        let lineCountSpan = ipt.parentElement.querySelector(".line-count");
        console.log(lineCountSpan);
        count += Number(lineCountSpan.innerHTML);
      });
    document.querySelector(".all-count11").innerHTML=count
}